#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
const int maxn = 100005;
struct letter
{
    int next;
    bool flag;
}node[maxn];
int main()
{
    // freopen("case.txt", "r", stdin);
    int s1, s2, n, i, count = 0, eidx, idx, next;
    char c;
    scanf("%d %d %d", &s1, &s2, &n);
    int words[maxn];
    vector<int> rwords[maxn];
    for (i = 0; i < n; i++)
    {
        scanf("%d %c %d", &idx, &c, &next);
        node[idx] = {next,false};
    }
    for(i = s1; i != -1; i = node[i].next)
    {
        node[i].flag = true;
    }
    for(i = s2; i != -1; i = node[i].next)
    {
        if(node[i].flag)
        {
            printf("%05d",i);
            return 0;
        }
    }
    cout << -1;

    return 0;
}